package com.levy.proxy;

import java.lang.reflect.Method;  

import net.sf.cglib.proxy.Enhancer;  
import net.sf.cglib.proxy.MethodInterceptor;  
import net.sf.cglib.proxy.MethodProxy;  
  
public class CGLibProxy implements MethodInterceptor {  
      
    private Object targetObject; //代理的目标对象  
      
    public Object createProxyInstance(Object tarObject){  
        this.targetObject = tarObject;   
        Enhancer enhancer = new Enhancer(); //该类用于生成代理器类  
          
        //将目标类指定为代理类的父类，产生的代理类是此目标类的一个子类，  
        //产生的这个子类会覆盖此目标类中的所有的非final修饰的方法  
        enhancer.setSuperclass(this.targetObject.getClass());  
        enhancer.setCallback(this); //设置回调对象为本身  
        return enhancer.create();  
    }  
  
    public Object intercept(Object proxy, Method method, Object[] args,  
            MethodProxy methodProxy) throws Throwable {  
    	PersonServiceBean bean = (PersonServiceBean) this.targetObject;  
        Object result = null;  
        if(bean.getUser() != null){  
            result = methodProxy.invoke(targetObject, args);  
            System.out.println("Proxy method excute sucessful." + bean.getUser());
        }  
        return result;  
    }  
}  


class PersonServiceBean{  
    private String user = null;  
  
    public PersonServiceBean() {  
    }  
  
    public PersonServiceBean(String user) {  
        this.user = user;  
    }  
  
    public String getUser() {  
        return user;  
    }  
  
    public void save(String name) {  
        System.out.println("我是save()方法" + name);  
    }  
  
    public void update(String name, int id) {  
        System.out.println("我是update()方法!");  
    }  
} 